package com.yy.service.impl;

import com.yy.domain.LoginUser;
import com.yy.exception.EntityNotFoundException;
import com.yy.service.UserContextService;
import com.yy.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

/**
 * @Description:
 * @ClassName: UserContextServiceImpl
 * @author: 姚欣宏
 * @date: 2023.11.10
 */
@Service
public class UserContextServiceImpl implements UserContextService {

    private final RedisCache redisCache;

    @Autowired
    public UserContextServiceImpl(RedisCache redisCache) {
        this.redisCache = redisCache;
    }

    @Override
    public LoginUser getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new AccessDeniedException("用户未认证");
        }
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        // Assuming 'user' inside 'LoginUser' is the object containing the ID.
        Long userId = ((LoginUser) userDetails).getUser().getId(); // Correctly fetch the user ID
        String redisKey = "login:" + userId;
        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        if (loginUser == null) {
            throw new EntityNotFoundException("缓存中未找到用户");
        }
        return loginUser;
    }

}

